package com.dingding.queue.queue.consumer.listener;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.facade.queue.dto.push.PushRequestDTO;
import com.dingding.queue.base.push.IPushDispatcher;

/**
 * 
 * @ClassName: PushMessageListener 
 * @Description: 极光推送队列消息监听
 * @author CHEHAUNBO 
 * @date 2016年6月13日 下午5:29:16
 * 
 */
@Component("pushMessageListener")
public class PushMessageListener implements MessageListener {

	private Logger log = Logger.getLogger(PushMessageListener.class);

	@Resource(name = "pushDispatcher")
	private IPushDispatcher pushDispatcher;

	@Override
	public Action consume(Message message, ConsumeContext context) {
		return parseQueueData(new String(message.getBody()));
	}

	/**
	 * 
	 * 从队列中读取数据
	 * 
	 * @Title: parseQueueData 
	 * @param queueData 队列中读取的数据 
	 * @author CHEHAUNBO
	 * 
	 */
	public Action parseQueueData(String queueData) {

		log.info("推送消息,原生队列中的消息内容为：" + queueData);

		PushRequestDTO pushRequestDTO = null;

		try {
			pushRequestDTO = JSONUtil.parseObject(queueData, PushRequestDTO.class);
		} catch (Exception e) {
			log.info("解析队列中的JSON数据出现问题！", e);
			return Action.CommitMessage;
		}
		log.info("推送别名： " + pushRequestDTO.getAliasId());
		// 推送
		boolean flag = pushDispatcher.dispatcher(pushRequestDTO);
		if (flag) {
			return Action.CommitMessage;
		} else {
			return Action.ReconsumeLater;
		}

	}

}
